package com.azusa.ktc_user.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    Environment environment;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求中的auth信息
        String auth = request.getHeader("auth");
        //解密前缀信息
        String prefix = environment.getProperty("jwt.config.prefix");
        if (auth != null && auth.startsWith(prefix)){
            //截取token
            String token = auth.substring(prefix.length());
            //解析token
            Claims claims = jwtUtil.parseJWT(token);
            if ("user".equals(claims.get("role"))){
                Object jtl = claims.get("jti");
                request.setAttribute("userId",jtl);//把登录用户放入请求体中
                return true;
            }
        }
        return false;
    }
}
